package cn.itcast.bos.web.action.base;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.service.base.FixedAreaService;
import cn.itcast.crm.domain.Customer;

@Controller // 交给spring管理
@Scope("prototype") // 多例
@Namespace("/") // 名称空间
@ParentPackage("json-default") // 父包
public class fixedAreaAction extends ActionSupport implements ModelDriven<FixedArea> {

	// 模型驱动
	private FixedArea fixedArea = new FixedArea();

	@Override
	public FixedArea getModel() {

		return fixedArea;
	}

	// 注入业务层

	@Autowired
	private FixedAreaService fixedAreaService;

	/**
	 * 
	 * 保存分区
	 */

	@Action(value = "fixedArea_save", results = {
			@Result(name = "success", type = "redirect", location = "pages/base/fixed_area.html") })
	public String save() {

		// 调用业务层将参数传递下去

		fixedAreaService.save(fixedArea);

		return SUCCESS;
	}

	/**
	 * 分页查询
	 */

	private int page;
	private int rows;

	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	@Action(value = "fixedArea_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		// 构造Pageable
		Pageable pageable = new PageRequest(page - 1, rows);
		// 构造条件查询对象
		Specification<FixedArea> specification = new Specification<FixedArea>() {

			@Override
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				// 构造查询条件
				if (StringUtils.isNotBlank(fixedArea.getId())) {
					// 根据 定区编号查询 等值
					Predicate p1 = cb.equal(root.get("id").as(String.class), fixedArea.getId());
					list.add(p1);
				}
				if (StringUtils.isNotBlank(fixedArea.getCompany())) {
					// 根据公司查询 模糊
					Predicate p2 = cb.like(root.get("company").as(String.class), "%" + fixedArea.getCompany() + "%");
					list.add(p2);
				}

				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		// 调用业务层，查询数据
		Page<FixedArea> pageData = fixedAreaService.findPageData(specification, pageable);

		// 压入值栈

		// 将数据封装到map里面
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("total", pageData.getTotalElements());// 所有的记录数
		map.put("rows", pageData.getContent());// 当前页面展示的所有数据

		// 将结果存到值栈，置顶
		ServletActionContext.getContext().getValueStack().push(map);

		return SUCCESS;
	}

	/**
	 * 查询没有关联分区的客户
	 */
	@Action(value = "fixedArea_findNoAssociationCustomers", results = { @Result(name = "success", type = "json") })
	public String findNoAssociationCustomers() {
		// 使用webClient调用webService接口
		Collection<? extends Customer> collection = WebClient
				.create("http://localhost:8081/crm_management/service/customerService/noAssociationCustomer")
				.accept(MediaType.APPLICATION_JSON).getCollection(Customer.class);
		// 将集合存入值栈
		ServletActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}

	/**
	 * 查询已经关定区的客户
	 */

	@Action(value = "fixedArea_findHasAssociationFixedAreaCustomers", results = {
			@Result(name = "success", type = "json") })
	public String findHasAssociationFixedAreaCustomers() {
		// 使用webClient调用webService接口
		Collection<? extends Customer> collection = WebClient.create(
				"http://localhost:8081/crm_management/service/customerService/associatedCustomer/" + fixedArea.getId())
				.accept(MediaType.APPLICATION_JSON).getCollection(Customer.class);
		// 将集合存入值栈
		ServletActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}

	/**
	 * 点击关联客户事件，将之前关联的客户从数据库中清空，然后将绑定客户框中的所有客户的定区id修改为指定的定区id
	 * associationCustomersToFixedArea
	 */
	// 接收传递的参数
	private String[] customerIds;// 放在方法里面不能用private修饰
	// 提供setter属性

	public void setCustomerIds(String[] customerIds) {
		this.customerIds = customerIds;
	}

	// 服务端需要的数据的一个ids的字符串，里面用,分隔开
	@Action(value = "fixedArea_associationCustomersToFixedArea", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/fixed_area.html") })
	public String associationCustomersToFixedArea() {
		// 非空校验
		String ids = "";
		if (customerIds != null && customerIds.length > 0) {
			for (String customerId : customerIds) {
				ids += customerId + ",";
			}
		}

		WebClient
				.create("http://localhost:8081/crm_management/service/customerService/associateCustomerToFixedArea?customerIdStr="
						+ ids + "&&fixedAreaId=" + fixedArea.getId())
				.type(MediaType.APPLICATION_JSON).put(null);// put请求

		// 遍历数组
		/*
		 * String ids = StringUtils.join(customerIds, ",");
		 * 
		 * if(StringUtils.isBlank(ids)){
		 * 
		 * ids="";
		 * 
		 * }
		 * 
		 * // 使用webClient调用webService接口 WebClient .create(
		 * "http://localhost:8081/crm_management/service/customerService/associateCustomerToFixedArea?customerIdStr="
		 * + ids + "&&fixedAreaId=" + fixedArea.getId())
		 * .type(MediaType.APPLICATION_JSON).put(null);//put请求
		 */
		return SUCCESS;
	}

	
	/**
	 * 将未关联的快递员关联到定区fixedArea_associationCourierToFixedArea
	 */
	//获取派件时间的id和快递员的id,与表单的name属性对应
	private Integer courierId;
	private Integer takeTimeId;
	
	
	
	public void setCourierId(Integer courierId) {
		this.courierId = courierId;
	}

	public void setTakeTimeId(Integer takeTimeId) {
		this.takeTimeId = takeTimeId;
	}

	@Action(value="fixedArea_associationCourierToFixedArea",results={@Result(name="success",location="/pages/base/fixed_area.html",type="redirect")})
	public String associationCourierToFixedArea(){
		
	//调用业务层，这里传递的参数有三个，第一个是定区的id,还有快递员的id，派件时间
		
		
		fixedAreaService.associationCourierToFixedArea(courierId,takeTimeId,fixedArea.getId());	
		
		return SUCCESS;
	}
	
	
}
